<?php

/*

***************************************
*                                     *
* Copyright 2011 David Matthew Pugh   *
* Contact Info:thebravedave@gmail.com *
*                                     *
***************************************

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

require_once 'WidgetShoppingCart.php';
require_once("./services/webservices.php");
if(!isset($_SESSION))
{
   session_start();     
}

$page_title="Review Order Before Payment";
include('./includes/header.php'); 
echo '<link href="./includes/tables.css" rel="stylesheet" type="text/css" />';

/* An express checkout transaction starts with a token, that
   identifies to PayPal your transaction
   In this example, when the script sees a token, the script
   knows that the buyer has already authorized payment through
   paypal.  If no token was found, the action is to send the buyer
   to PayPal to first authorize payment
   */

if(isset($_REQUEST['token']))
{
    $token = $_REQUEST['token']; 
}

if(! isset($token)) 
{

        /* The servername and serverport tells PayPal where the buyer
           should be directed back to after authorizing payment.
           In this case, it's the local webserver that is running this script
           Using the servername and serverport, the return URL is the first
           portion of the URL that buyers will return to after authorizing payment
           */
           $serverName = $_SERVER['SERVER_NAME'];
           $serverPort = $_SERVER['SERVER_PORT'];
           //$url=dirname('http://'.$serverName.':'.$serverPort.$_SERVER['REQUEST_URI']);
           $url = "https://localhost/projects/ecommerce_merchant_exchange_package";

           $currencyCodeType= "USD";
           $paymentType= "SALE";
   
         
           $personName        =  $_SESSION['shipping_first_name'] . " " . $_SESSION['shipping_last_name'];
           $SHIPTOSTREET      =  $_SESSION['shipping_street_address'];
           $SHIPTOCITY        =  $_SESSION['shipping_city'];
           $SHIPTOSTATE       =  $_SESSION['shipping_state'];
           $SHIPTOCOUNTRYCODE =  "US";
           $SHIPTOZIP         =  $_SESSION['shipping_zip_code'];

                  
                 
   $cart = unserialize($_SESSION['cart']);                 
   $itemstringconcat = "";  
   $itemnameconcat = "";
   $itemamtconcat = "";
   $itemqtyconcat = "";
   $itemcount = 0;    
   $itemtotal = 0;  

   foreach ($cart->items as $id => $info)            
   {   
        $cart_sw_id = $info['sw_id'];        
        $cart_gw_id = $info['gw_id'];
        $category = $info['category'];
        $name = $info['name']; 
        $name = urldecode($name);
        $qty = $info['qty'];
        $price = number_format($info['price'], 2, '.', '');
        $subtotal = $qty * $price;
        
        $itemtotal = $itemtotal + $subtotal;
         
        if($cart_sw_id == "")
        {
           $itemnameconcat .= 'L_NAME' . $itemcount . '=' . $name . '&';
           $itemqtyconcat .= 'L_QTY' . $itemcount . '=' . $qty . '&'; 
           $itemamtconcat .= 'L_AMT' . $itemcount . '=' . $price . '&';
           
        }
        else
        {
            $xml_name = new SimpleXMLElement($name);
            $gen_name = $xml_name->gw_name;
            
            $xml_build = "";
            foreach($xml_name->Item as $eachitem1)
            {
                $desc_category = $eachitem1->category;
                $descriptor = $eachitem1->descriptor;    
                $xml_build .= $desc_category . ":" . $descriptor . " ";
            }
            $name = $gen_name . '[' . $xml_build . ']';
            $itemnameconcat .= 'L_NAME' . $itemcount . '=' . $name . '&';
            $itemamtconcat .= 'L_AMT' . $itemcount . '=' . $price . '&'; 
            $itemqtyconcat .= 'L_QTY' . $itemcount . '=' . $qty . '&';  
        }
        
        $itemcount++;             
   } 
   $itemstringconcat = $itemnameconcat . $itemamtconcat . $itemqtyconcat; 


         /* The returnURL is the location where buyers return when a
            payment has been succesfully authorized.
            The cancelURL is the location buyers are sent to when they hit the
            cancel button during authorization of payment during the PayPal flow
            */

           $returnURL =urlencode($url.'/paypal.php?currencyCodeType='.$currencyCodeType.'&paymentType='.$paymentType);    
           $cancelURL =urlencode("$url/SetExpressCheckout.php?paymentType=$paymentType" );

         /* Construct the parameter string that describes the PayPal payment
            the varialbes were set in the web form, and the resulting string
            is stored in $nvpstr
          */  
       
           $itemamt = $_SESSION['items_total'];   
           $shippingtotal = $_SESSION['shipping_total'];
           $amount = (double)$itemamt + (double)$shippingtotal;
           $itemshippingconcat = "&ITEMAMT=" . $itemamt . "&SHIPPINGAMT=" . $shippingtotal; 
           
           
           
           
           /*
            * Setting up the Shipping address details
            */
           $shiptoAddress = "&SHIPTONAME=$personName&SHIPTOSTREET=$SHIPTOSTREET&SHIPTOCITY=$SHIPTOCITY&SHIPTOSTATE=$SHIPTOSTATE&SHIPTOCOUNTRYCODE=$SHIPTOCOUNTRYCODE&SHIPTOZIP=$SHIPTOZIP";
           

           
            $nvpstr="&NOSHIPPING=1&ADDRESSOVERRIDE=1&" . $shiptoAddress . "&AMT=" . $amount .  $itemshippingconcat . "&" . $itemstringconcat . "ReturnUrl=".$returnURL."&CANCELURL=".$cancelURL .
            "&CURRENCYCODE=".$currencyCodeType."&PAYMENTACTION=".$paymentType;
           
            
           
             /* Make the call to PayPal to set the Express Checkout token
            If the API call succeded, then redirect the buyer to PayPal
            to begin to authorize payment.  If an error occured, show the
            resulting errors
            */

          $paypalhttppost = new paypalhttppost();
          $resArray = $paypalhttppost->SetExpressCheckout($nvpstr);
     
          
           $_SESSION['reshash']=$resArray;

           $ack = strtoupper($resArray["ACK"]);

         
           
           if($ack=="SUCCESS")
           {
                    // Redirect to paypal.com here
                    $token = urldecode($resArray["TOKEN"]);
                    $payPalURL = "https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=$token";
                    header("Location: ".$payPalURL);
           } 
           else  
           {
                     //Redirecting to APIError.php to display errors.
                       $location = "APIError.php";
                       header("Location: $location");
           }
} 
else 
{
         /* At this point, the buyer has completed in authorizing payment
            at PayPal.  The script will now call PayPal with the details
            of the authorization, incuding any shipping information of the
            buyer.  Remember, the authorization is not a completed transaction
            at this state - the buyer still needs an additional step to finalize
            the transaction
            */

           $token =urlencode( $_REQUEST['token']);

         /* Build a second API request to PayPal, using the token as the
            ID to get the details on the payment authorization
            */
           $nvpstr="&TOKEN=".$token;

          // $nvpstr = $nvpHeader.$nvpstr;
         /* Make the API call and store the results in an array.  If the
            call was a success, show the authorization details, and provide
            an action to complete the payment.  If failed, show the error
            */
          // $resArray=hash_call("GetExpressCheckoutDetails",$nvpstr);
          $paypalhttppost = new paypalhttppost();
          $resArray = $paypalhttppost->PPWebservice("GetExpressCheckoutDetails",$nvpstr);  

           $ack = strtoupper($resArray["ACK"]);

           if($ack == 'SUCCESS' || $ack == 'SUCCESSWITHWARNING')
           {
               
               $_SESSION['payment_first_name'] = $resArray['FIRSTNAME'];
               $_SESSION['payment_last_name'] = $resArray['LASTNAME'];
               $_SESSION['payment_payerid'] = $resArray['PAYERID'];
               $_SESSION['payment_email'] = $resArray['EMAIL'];
               
              
               require_once "GetExpressCheckoutDetails.php";

           } 
           else  
           {
                //Redirecting to APIError.php to display errors.
                $location = "APIError.php";
                header("Location: $location");
           }
}
?>  

